import { NextResponse } from 'next/server'
import prisma from '@/lib/prisma'
import {getUser} from '@/lib/authUtils'


export async function GET(request: Request): Promise<Response> {
    try {
      const userid = await getUser(request)
      if (!userid) {
        return new Response(JSON.stringify({ error: '未授权或登录信息过期，请登录' }), {
          status: 401,
          headers: {
            'Content-Type': 'application/json'
          }
        })
      }
      if (userid instanceof NextResponse) {
        return userid
      }
  
      const topics = await prisma.vms_topic.findMany({
        where: {
          user_id: userid
        },
        orderBy: {
          pxh: 'asc'
        },
        select: {
            id: true,
            name: true,
            pxh: true,
            copies: {
              orderBy: {
                pxh: 'asc'
              },
              select: {
                id: true,
                title: true,
                pxh: true,
                topic_id: true
              }
            }
        }
      })
      
      
      return new Response(JSON.stringify(topics), {
        headers: {
          'Content-Type': 'application/json'
        }
      })
    } catch (error: any) {
      return new Response(JSON.stringify({ error: error.message || '获取话题失败' }), {
        status: 500,
        headers: {
          'Content-Type': 'application/json'
        }
      })
    }
  }